from fastapi import APIRouter, HTTPException, Depends, Query
from typing import List, Optional
from pydantic import BaseModel, Field
from datetime import datetime
from service.room_service import RoomService
from controller.base_controller import BaseController


class CreateRoomRequest(BaseModel):
    """创建房间请求模型"""
    room_name: str = Field(..., min_length=1, max_length=100, description="房间名称")
    description: Optional[str] = Field(None, max_length=500, description="房间描述")


class UpdateRoomRequest(BaseModel):
    """更新房间请求模型"""
    room_name: Optional[str] = Field(None, min_length=1, max_length=100, description="房间名称")
    description: Optional[str] = Field(None, max_length=500, description="房间描述")
    is_active: Optional[bool] = Field(None, description="是否激活")


class RoomResponse(BaseModel):
    """房间响应模型"""
    room_id: str
    room_name: str
    description: Optional[str]
    is_active: bool
    created_at: datetime
    updated_at: datetime


class RoomStatisticsResponse(BaseModel):
    """房间统计响应模型"""
    room_id: str
    room_name: str
    is_active: bool
    total_sessions: int
    recent_sessions_30d: int
    last_monitoring_time: Optional[datetime]
    created_at: datetime
    updated_at: datetime


class RoomController(BaseController):
    """房间管理控制器"""
    
    def __init__(self):
        super().__init__()
        self.router = APIRouter(prefix="/api/rooms", tags=["房间管理"])
        self.room_service = RoomService()
        self._register_routes()
    
    def _register_routes(self):
        """注册路由"""
        
        @self.router.post("/", response_model=RoomResponse, summary="创建房间")
        async def create_room(request: CreateRoomRequest):
            """
            创建新房间
            
            - **room_name**: 房间名称（必填）
            - **description**: 房间描述（可选）
            """
            try:
                room = await self.room_service.create_room(
                    room_name=request.room_name,
                    description=request.description
                )
                return RoomResponse(
                    room_id=room.room_id,
                    room_name=room.room_name,
                    description=room.description,
                    is_active=room.is_active,
                    created_at=room.created_at,
                    updated_at=room.updated_at
                )
            except Exception as e:
                raise HTTPException(status_code=500, detail=f"创建房间失败: {str(e)}")
        
        @self.router.get("/", response_model=List[RoomResponse], summary="获取房间列表")
        async def get_rooms(
            active_only: bool = Query(False, description="是否只返回激活的房间"),
            keyword: Optional[str] = Query(None, description="搜索关键词")):
            """
            获取房间列表
            
            - **active_only**: 是否只返回激活的房间
            - **keyword**: 搜索关键词（搜索房间名称和描述）
            """
            try:
                if keyword:
                    rooms = await self.room_service.search_rooms(keyword)
                elif active_only:
                    rooms = await self.room_service.get_active_rooms()
                else:
                    rooms = await self.room_service.get_all_rooms()
                
                return [
                    RoomResponse(
                        room_id=room.room_id,
                        room_name=room.room_name,
                        description=room.description,
                        is_active=room.is_active,
                        created_at=room.created_at,
                        updated_at=room.updated_at
                    )
                    for room in rooms
                ]
            except Exception as e:
                raise HTTPException(status_code=500, detail=f"获取房间列表失败: {str(e)}")
        
        @self.router.get("/{room_id}", response_model=RoomResponse, summary="获取房间详情")
        async def get_room(room_id: str):
            """
            根据房间ID获取房间详情
            
            - **room_id**: 房间唯一标识符
            """
            room = await self.room_service.get_room_by_id(room_id)
            if not room:
                raise HTTPException(status_code=404, detail="房间不存在")
            
            return RoomResponse(
                room_id=room.room_id,
                room_name=room.room_name,
                description=room.description,
                is_active=room.is_active,
                created_at=room.created_at,
                updated_at=room.updated_at
            )
        
        @self.router.put("/{room_id}", response_model=RoomResponse, summary="更新房间信息")
        async def update_room(room_id: str, request: UpdateRoomRequest):
            """
            更新房间信息
            
            - **room_id**: 房间唯一标识符
            - **room_name**: 新的房间名称（可选）
            - **description**: 新的房间描述（可选）
            - **is_active**: 是否激活（可选）
            """
            # 只更新非空字段
            update_data = {}
            if request.room_name is not None:
                update_data['room_name'] = request.room_name
            if request.description is not None:
                update_data['description'] = request.description
            if request.is_active is not None:
                update_data['is_active'] = request.is_active
            
            if not update_data:
                raise HTTPException(status_code=400, detail="至少需要提供一个要更新的字段")
            
            room = await self.room_service.update_room(room_id, **update_data)
            if not room:
                raise HTTPException(status_code=404, detail="房间不存在")
            
            return RoomResponse(
                room_id=room.room_id,
                room_name=room.room_name,
                description=room.description,
                is_active=room.is_active,
                created_at=room.created_at,
                updated_at=room.updated_at
            )
        
        @self.router.post("/{room_id}/activate", summary="激活房间")
        async def activate_room(room_id: str):
            """
            激活房间
            
            - **room_id**: 房间唯一标识符
            """
            success = await self.room_service.activate_room(room_id)
            if not success:
                raise HTTPException(status_code=404, detail="房间不存在")
            
            return {"message": "房间激活成功", "room_id": room_id}
        
        @self.router.post("/{room_id}/deactivate", summary="停用房间")
        async def deactivate_room(room_id: str):
            """
            停用房间
            
            - **room_id**: 房间唯一标识符
            """
            success = await self.room_service.deactivate_room(room_id)
            if not success:
                raise HTTPException(status_code=404, detail="房间不存在")
            
            return {"message": "房间停用成功", "room_id": room_id}
        
        @self.router.delete("/{room_id}", summary="删除房间")
        async def delete_room(room_id: str):
            """
            删除房间
            
            注意：只有在没有关联监测数据时才能删除房间
            
            - **room_id**: 房间唯一标识符
            """
            success = await self.room_service.delete_room(room_id)
            if not success:
                # 检查房间是否存在
                room = await self.room_service.get_room_by_id(room_id)
                if not room:
                    raise HTTPException(status_code=404, detail="房间不存在")
                else:
                    raise HTTPException(status_code=400, detail="房间有关联数据，无法删除")
            
            return {"message": "房间删除成功", "room_id": room_id}
        
        @self.router.get("/{room_id}/statistics", response_model=RoomStatisticsResponse, summary="获取房间统计信息")
        async def get_room_statistics(room_id: str):
            """
            获取房间统计信息
            
            包括监测会话数量、最近活动时间等统计数据
            
            - **room_id**: 房间唯一标识符
            """
            stats = await self.room_service.get_room_statistics(room_id)
            if not stats:
                raise HTTPException(status_code=404, detail="房间不存在")
            
            return RoomStatisticsResponse(**stats)
        
        @self.router.post("/{room_id}/validate", summary="验证房间访问权限")
        async def validate_room_access(room_id: str):
            """
            验证房间访问权限
            
            检查房间是否存在且处于激活状态
            
            - **room_id**: 房间唯一标识符
            """
            has_access = await self.room_service.validate_room_access(room_id)
            
            return {
                "room_id": room_id,
                "has_access": has_access,
                "message": "有访问权限" if has_access else "无访问权限或房间不存在"
            }